<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" prop="id" align="center" width="65" />
      <el-table-column label="商品名称" prop="goodsName" align="center" />
      <el-table-column label="商品图片" prop="goodsImg" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.goodsImg" width="100" alt="">
        </template>
      </el-table-column>
      <el-table-column label="商品描述" prop="goodsDesc" align="center" />
      <el-table-column label="商品价格" prop="goodsPrice" align="center" />
      <el-table-column label="商品状态" prop="goodsType" align="center">
        <template slot-scope="scope">
          {{ ['下线', '上线'][scope.row.goodsType] }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item :label-width="formLabelWidth" label="商品名称">
          <el-input v-model="temp.goodsName" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="商品价格">
          <el-input v-model="temp.goodsPrice" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item :label-width="formLabelWidth" label="商品描述">
          <el-input v-model="temp.goodsDesc" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="商品图片">
          <el-upload :on-preview="handlePreview" :on-remove="handleRemove" :file-list="temp.fileList" :action="host+'/admin/img/0'" :headers="headers" :limit="1" :on-success="handleSuccess" class="upload-demo" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="上线线">
          <el-select v-model="temp.goodsType">
            <el-option key="0" :value="0" label="下线">下线</el-option>
            <el-option key="1" :value="1" label="上线">上线</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {
        fetchProductsAjax,
        addProductAjax,
        updateProductAjax,
        delProductAjax
        // fetchRoleAjax
    } from "@/api/product";
    import waves from "@/directive/waves"; // Waves directive
    // import { parseTime } from "@/utils";
    import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

    export default {
        name: "Products",
        components: { Pagination },
        directives: { waves },
        filters: {},

        data() {
            return {
                tableKey: 0,
                list: [],
                total: 0,
                listLoading: true,
                listQuery: {
                    pageNum: 1,
                    pageSize: 10
                },
                textMap: {
                    create: "新增商品",
                    detail: "商品详情"
                },
                downloadLoading: false,
                dialogFormVisible: false,
                temp: {},
                formLabelWidth: "150px",
                rules: {},
                dialogStatus: "",
                tempList: [],
                headers: { Authorization: 'Bearer ' + this.$store.state.user.token },
                host: process.env.BASE_API
            };
        },
        computed: {
            goosInfo() {
                return { goodsName: this.temp.goodsName, goodDesc: this.temp.goodsDesc };
            }
        },
        created() {
            this.getList();
        },
        methods: {
            handleSuccess(file, fileList) {
                this.temp.fileList = [];
                this.temp.fileList.push({
                    name: fileList.name,
                    url: file.data.file
                })
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            getList() {
                this.listLoading = true;
                this.listLoading = false;
                this.listLoading = true;
                fetchProductsAjax(this.listQuery).then(response => {
                    // if (respons.data.data.) {

                    // }
                    this.list = response.data.data.pageData;
                    this.total = response.data.data.maxCount;
                    this.listLoading = false;
                });
            },

            handleFilter() {
                this.listQuery.page = 1;
                this.getList();
            },

            handleCreate() {
                this.temp = {};
                this.dialogStatus = "create";
                this.dialogFormVisible = true;
                this.$nextTick(() => {
                    this.$refs["dataForm"].resetFields();
                });
            },

            createData() {
                this.$refs["dataForm"].validate(valid => {
                    if (valid) {
                        const formData = new FormData();
                        formData.append("goodsName", this.temp.goodsName); // 这就是给formData添加新的表单数据的形式
                        formData.append("goodsDesc", this.temp.goodsDesc);
                        formData.append("goodsType", this.temp.goodsType);
                        formData.append("goodsPrice", this.temp.goodsPrice);
                        formData.append("goodsImg", this.temp.fileList[0].url);
                        addProductAjax(formData).then(() => {
                            this.dialogFormVisible = false;
                            this.$notify({
                                title: "成功",
                                message: "创建成功",
                                type: "success",
                                duration: 2000
                            });
                            this.getList();
                        });
                    }
                });
            },
            handleUpdate(row) {
                row.fileList = [{
                    name: row.goodsName,
                    url: row.goodsImg
                }]
                this.temp = Object.assign({}, row); // copy obj
                this.dialogStatus = "update";
                this.dialogFormVisible = true;
                this.$nextTick(() => {
                    this.$refs["dataForm"].clearValidate();
                });
            },
            updateData() {
                this.$refs["dataForm"].validate(valid => {
                    if (valid) {
                        this.temp.goodsImg = this.temp.fileList[0].url;
                        const tempData = Object.assign({}, this.temp);
                        updateProductAjax(tempData).then(() => {
                            this.dialogFormVisible = false;
                            this.$notify({
                                title: "成功",
                                message: "更新成功",
                                type: "success",
                                duration: 2000
                            });
                            this.getList();
                        });
                    }
                });
            },
            handleDelete(row) {
                this.$confirm("确认删除该条数据吗?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    delProductAjax(row).then(res => {
                        // const index = this.list.indexOf(row);
                        // this.list.splice(index, 1);
                        if (res.data.code !== 0 || res.data.data.length < 0) {
                            this.$message({
                                message: "删除失败",
                                type: "error",
                                duration: 5 * 1000
                            });
                            return;
                        }
                        this.$notify({
                            title: "成功",
                            message: "删除成功",
                            type: "success",
                            duration: 2000
                        });
                        this.getList();
                    });
                });
            }
        }
    };
</script>
